package com.banzhi.shop.activity;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.data.Address_Data;
import com.banzhi.shop.data.BeCityPartnersData;
import com.banzhi.shop.data.PartnerApplicationBean;

import com.banzhi.shop.entity.ChoiceAddress.Address;
import com.banzhi.shop.entity.ShopInformation.Shop_Data;
import com.banzhi.shop.model.CallBack.BeCityPartnersCallBack;
import com.banzhi.shop.model.CallBack.GetAddressCallBack;
import com.banzhi.shop.model.CallBack.InputPicturesCallBack;
import com.banzhi.shop.model.CallBack.PartnerApplictionCallBack;
import com.banzhi.shop.model.IBeCityPartnersModel;
import com.banzhi.shop.model.IGetAddressModel;
import com.banzhi.shop.model.Impl.BeCityPartnersImpl;


import com.banzhi.shop.model.Impl.GetAddressImpl;
import com.banzhi.shop.model.Impl.InputPictureImpl;
import com.banzhi.shop.model.Impl.PartnerApplicationImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.BitmapUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.PermissionsChecker;
import com.banzhi.shop.utils.TemplatePopupwindowUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import com.nostra13.universalimageloader.utils.L;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import cn.carbswang.android.numberpickerview.library.NumberPickerView;

import static com.banzhi.shop.activity.PersonDetailActivity.PERMISSIONS;
//合伙人申请

public class PartnerApplicationActivity extends BaseActivity implements View.OnClickListener, InputPicturesCallBack, PartnerApplictionCallBack, BeCityPartnersCallBack, GetAddressCallBack {

    private ImageView mIvBackPartner;
    private EditText mEtName;
    private EditText mEtPhone;
    private EditText mEtAddressPartner;
    //身份证号
    private EditText mEtIdentityId;
    private ImageView mIvZheng;
    private ImageView mIvFan;
    // private EditText mEtMailbox;
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    private Button mBtnSubmitReview;
    private InputPictureImpl mPicModel;
    private PartnerApplicationImpl mModel;
    private PartnerApplicationBean mPartnerApplicationBean;
    /**
     * 上传身份证正面后返回的头像的网络地址
     */
    private String zhengURL;
    //上传身份证反面返回的头像的网络地址
    private String fanURL;
    private Bitmap bitmap;

    /**
     * 裁剪后的照片文件
     */
    private File Imagefile;
    private String mCheck;

    private BeCityPartnersData mPartnersData;

    private String Check;
    private String Ispay;
    private String mDenyReason;
    private String mIspay;
    private TextView mTvAddress;
    private GetAddressImpl mGetAddressModel;

    /**
     * 选择省市区
     */
    private LinearLayout llchoiceaddress;
    //  private TextView tvaddress;
    private String province;
    private String city;
    private String district;
    //省市区地址的实体类集合
    private List<Address.DataBean.ChildrenBean> citylist = new ArrayList<>();
    private List<String> arealist = new ArrayList<>();

    //省市区地址的集合
    private List<String> pid = new ArrayList<>();
    private List<String> cid = new ArrayList<>();
    private Address_Data data;
    private Address address;
    private LinearLayout mLlChoiceAddress;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_partner_application2);
        Translucent.setTranslucent(this);
        mPermissionsChecker = new PermissionsChecker(this);
        mPicModel = new InputPictureImpl();
        mModel = new PartnerApplicationImpl();

        BeCityPartnersImpl model = new BeCityPartnersImpl();
        model.beCityPartners(this);

        mGetAddressModel = new GetAddressImpl();
        mGetAddressModel.getAddress(this);
        Intent intent2 = getIntent();

        data = (Address_Data) intent2.getSerializableExtra("data");


        Intent intent = getIntent();
        mCheck = intent.getStringExtra("mCheck");
        mIspay = intent.getStringExtra("mIspay");
        if ("2".equals(mCheck)) {
            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
            mModel.getPartnerApplicationData(this);
            Log.e("GetPartner:", "获取数据1");
            //  showView();
        }
        initView();
        initListener();
    }

    private void showView() {

      //  Log.e("showView:", "显示数据");
        mEtName.setText(MyApp.loginMessage.getString("username", ""));
        mEtPhone.setText(MyApp.loginMessage.getString("mobile", ""));
        mEtAddressPartner.setText(MyApp.loginMessage.getString("address", ""));
        mEtIdentityId.setText(MyApp.loginMessage.getString("userid", ""));
        if (ASUtils.isCanUse(MyApp.loginMessage.getString("imguserida", ""))) {
            Picasso.with(this).load(MyApp.loginMessage.getString("imguserida", "")).placeholder(R.mipmap.zhanweitu2).into(mIvZheng);
        }
        if (ASUtils.isCanUse(MyApp.loginMessage.getString("imguseridb", ""))) {
            Picasso.with(this).load(MyApp.loginMessage.getString("imguseridb", "")).placeholder(R.mipmap.zhanweitu2).into(mIvFan);
        }


    }

    private void initView() {
        Log.e("initView:", "初始化数据");
        mIvBackPartner = (ImageView) findViewById(R.id.iv_back_partner);
        mEtName = (EditText) findViewById(R.id.et_name_partner);
        mEtPhone = (EditText) findViewById(R.id.et_phone_partner);
        mEtAddressPartner = (EditText) findViewById(R.id.et_address_partner);
        mTvAddress = (TextView) findViewById(R.id.tv_address);
        mEtIdentityId = (EditText) findViewById(R.id.et_identity_id);
        mIvZheng = (ImageView) findViewById(R.id.iv_zheng);
        mIvFan = (ImageView) findViewById(R.id.iv_fan);
        mBtnSubmitReview = (Button) findViewById(R.id.btn_submit_review);
        mLlChoiceAddress = (LinearLayout) findViewById(R.id.ll_choice_address);


    }


    private void initListener() {
        mIvBackPartner.setOnClickListener(this);
        mIvZheng.setOnClickListener(this);
        mIvFan.setOnClickListener(this);
        mBtnSubmitReview.setOnClickListener(this);
        mLlChoiceAddress.setOnClickListener(this);
    }

    private String type;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back_partner:
                finish();
                break;
            case R.id.ll_choice_address:
                choiceCity();
                //隐藏键盘
                InputMethodManager inputMethodManager = (InputMethodManager)PartnerApplicationActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                 if(getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN){
                    inputMethodManager.hideSoftInputFromWindow(PartnerApplicationActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }

                break;
            case R.id.iv_zheng:
                type = "zheng";
                showImagePopwindow();
                //隐藏键盘
                InputMethodManager inputMethodManager2 = (InputMethodManager)PartnerApplicationActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                if(getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN){
                    inputMethodManager2.hideSoftInputFromWindow(PartnerApplicationActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }

                break;
            case R.id.iv_fan:
                type = "fan";
                showImagePopwindow();
                //隐藏键盘
                InputMethodManager inputMethodManager3 = (InputMethodManager)PartnerApplicationActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                if(getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN){
                    inputMethodManager3.hideSoftInputFromWindow(PartnerApplicationActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }

                break;
            case R.id.btn_submit_review:
               // ToastUtils.makeToastShort("点击1");
                if (!"2".equals(mCheck)) {
                    Log.e("第一次上传数据:", "第一次提交数据");
                    String name = mEtName.getText().toString().trim();
                    String phone = mEtPhone.getText().toString().trim();
                    String address = mEtAddressPartner.getText().toString().trim();
                    String identity = mEtIdentityId.getText().toString().trim();
                    String citys = mTvAddress.getText().toString().trim();

                    if (!ASUtils.isCanUse(mEtName.getText().toString().trim())) {
                        ToastUtils.makeToastShort("请先输入姓名");
                    } else if (!ASUtils.isCanUse(mEtPhone.getText().toString().trim())) {
                        ToastUtils.makeToastShort("请先输入电话号码");

                    } /*else if (mEtPhone.getText().toString().trim().length() < 11) {
                    ToastUtils.makeToastShort("电话号码不符合规范");
                }*/ else if (citys.isEmpty()) {
                        ToastUtils.makeToastShort("请选择地址");
                    } else if (!ASUtils.isCanUse(mEtAddressPartner.getText().toString().trim())) {
                        ToastUtils.makeToastShort("请先输入地址");
                    } else if (!ASUtils.isCanUse(mEtIdentityId.getText().toString().trim())) {
                        ToastUtils.makeToastShort("请先输入身份证号");
                    } else if (!ASUtils.isCanUse(zhengURL)) {
                        ToastUtils.makeToastShort("请先上传身份证正面照");
                    } else if (!ASUtils.isCanUse(fanURL)/*||!ASUtils.isCanUse( MyApp.loginMessage.getString("imguseridb", ""))*/) {
                        ToastUtils.makeToastShort("请先上传身份证反面照");
                    } else if (ASUtils.isCanUse(zhengURL)) {
                        if (ASUtils.isCanUse(fanURL)) {
                            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                            mModel.applyForPartnerData(name, phone, citys + address, identity, zhengURL, fanURL, this);
                        }
                    }
                } else {
                    String name = mEtName.getText().toString().trim();
                    String phone = mEtPhone.getText().toString().trim();
                    String address = mEtAddressPartner.getText().toString().trim();
                    String identity = mEtIdentityId.getText().toString().trim();
                    String citys = mTvAddress.getText().toString().trim();
                    Log.e("第二次次上传数据:", "第二次提交数据");
                    if (!ASUtils.isCanUse(mEtName.getText().toString().trim())) {
                        ToastUtils.makeToastShort("请先输入姓名");
                    } else if (!ASUtils.isCanUse(mEtPhone.getText().toString().trim())) {
                        ToastUtils.makeToastShort("请先输入电话号码");
                    }/* else if (citys.isEmpty()) {
                        ToastUtils.makeToastShort("请选择地址");
                    }*/ else if (!ASUtils.isCanUse(mEtAddressPartner.getText().toString().trim())) {
                        ToastUtils.makeToastShort("请先输入地址");
                    } else if (!ASUtils.isCanUse(mEtIdentityId.getText().toString().trim())) {
                        ToastUtils.makeToastShort("请先输入身份证号");
                    } else if (!ASUtils.isCanUse(zhengURL)&&!ASUtils.isCanUse(fanURL)) {
                        zhengURL = MyApp.loginMessage.getString("imguserida", "");
                        fanURL = MyApp.loginMessage.getString("imguseridb", "");
                        // ToastUtils.makeToastShort("请先上传身份证正面照");
                        // ToastUtils.makeToastShort("请先上传身份证反面照");
                        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                        mModel.changePartnerApplicationData(name, phone, citys + address, identity, zhengURL, fanURL, this);
                        Log.e("ChangePartner:", "提交审核");
                    } else if (!ASUtils.isCanUse(zhengURL)&&ASUtils.isCanUse(fanURL)) {
                        zhengURL = MyApp.loginMessage.getString("imguserida", "");
                        // ToastUtils.makeToastShort("请先上传身份证正面照");
                        // ToastUtils.makeToastShort("请先上传身份证反面照");
                        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                        mModel.changePartnerApplicationData(name, phone, citys + address, identity, zhengURL, fanURL, this);
                        Log.e("ChangePartner:", "提交审核");
                    }else if (!ASUtils.isCanUse(fanURL)&&ASUtils.isCanUse(zhengURL)) {
                        fanURL = MyApp.loginMessage.getString("imguseridb", "");
                        // ToastUtils.makeToastShort("请先上传身份证正面照");
                        // ToastUtils.makeToastShort("请先上传身份证反面照");
                        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                        mModel.changePartnerApplicationData(name, phone, citys + address, identity, zhengURL, fanURL, this);
                        Log.e("ChangePartner:", "提交审核");
                    }  else if (ASUtils.isCanUse(zhengURL)) {
                        if (ASUtils.isCanUse(fanURL)) {
                            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                            mModel.changePartnerApplicationData(name, phone, citys + address, identity, zhengURL, fanURL, this);
                            Log.e("ChangePartner:", "提交审核");
                        }
                    }
                }
                break;
        }
    }

    private NumberPickerView npv_province;
    private NumberPickerView npv_city;
    private NumberPickerView npv_area;

    /**
     * 选择省市区
     */

    private void choiceCity() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.popupwindow_city, null);
        npv_province = (NumberPickerView) popView.findViewById(R.id.picker_province);
        npv_city = (NumberPickerView) popView.findViewById(R.id.picker_city);
        npv_area = (NumberPickerView) popView.findViewById(R.id.picker_area);

        //将省份数据显示在选择器上
        npv_province.refreshByNewDisplayedValues(pid.toArray(new String[pid.size()]));

        final Button btntrue = (Button) popView.findViewById(R.id.btn_true);
        final Button btncancel = (Button) popView.findViewById(R.id.btn_cancel);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失

        //获取默认城市等于0的省份的数据
        if (pid.size() > 0) {
            province = pid.get(0);
        } else {
            province = "";
        }
        citylist.clear();
        citylist.addAll(address.getData().get(0).getChildren());
        cid.clear();
        for (Address.DataBean.ChildrenBean Bean : citylist) {
            cid.add(Bean.getText());
        }
        //将城市数据显示在选择器上
        if (cid.size() > 0) {
            npv_city.refreshByNewDisplayedValues(cid.toArray(new String[cid.size()]));
            city = cid.get(0);
        } else {
            npv_city.refreshByNewDisplayedValues(new String[]{""});
            city = "";
        }

        arealist.clear();
        if (citylist.size() > 0) {
            arealist.addAll(citylist.get(0).getChildren());
            //将城市数据显示在选择器上
            if (arealist.size() > 0) {
                npv_area.refreshByNewDisplayedValues(arealist.toArray(new String[arealist.size()]));
                district = arealist.get(0);
            } else {
                npv_area.refreshByNewDisplayedValues(new String[]{""});
                district = "";
            }
        }


        NumberPickerView.OnValueChangeListener nplistener = new NumberPickerView.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPickerView picker, int oldVal, int newVal) {
                switch (picker.getId()) {
                    case R.id.picker_province:
                        province = pid.get(newVal);

                        citylist.clear();
                        citylist.addAll(address.getData().get(newVal).getChildren());
                        cid.clear();
                        for (Address.DataBean.ChildrenBean Bean : citylist) {
                            cid.add(Bean.getText());
                        }
                        //将城市数据显示在选择器上
                        if (cid.size() > 0) {
                            npv_city.refreshByNewDisplayedValues(cid.toArray(new String[cid.size()]));
                            city = cid.get(0);
                        } else {
                            npv_city.refreshByNewDisplayedValues(new String[]{""});
                            city = "";
                        }

                        arealist.clear();
                        if (citylist.size() > 0) {
                            arealist.addAll(citylist.get(0).getChildren());
                            //将城市数据显示在选择器上
                            if (arealist.size() > 0) {
                                npv_area.refreshByNewDisplayedValues(arealist.toArray(new String[arealist.size()]));
                                district = arealist.get(0);
                            } else {
                                npv_area.refreshByNewDisplayedValues(new String[]{""});
                                district = "";
                            }
                        }
                        break;
                    case R.id.picker_city:
                        city = cid.get(newVal);
                        arealist.clear();
                        arealist.addAll(citylist.get(newVal).getChildren());
                        //将城市数据显示在选择器上
                        if (arealist.size() > 0) {
                            npv_area.refreshByNewDisplayedValues(arealist.toArray(new String[arealist.size()]));
                            district = arealist.get(0);
                        } else {
                            npv_area.refreshByNewDisplayedValues(new String[]{""});
                            district = "";
                        }
                        break;
                    case R.id.picker_area:
                        district = arealist.get(newVal);
                        break;
                }

            }
        };
        npv_province.setOnValueChangedListener(nplistener);
        npv_city.setOnValueChangedListener(nplistener);
        npv_area.setOnValueChangedListener(nplistener);
        btntrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvAddress.setText(province + city + district);
                LogUtils.d("地址数据：", "province=" + province + "city=" + city + "+district=" + district);
                popWindow.dismiss();
            }
        });
        btncancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    private static final int CODE_GALLERY_REQUEST = 0x1;
    private static final int CODE_CAMERA_REQUEST = 0x2;
    private static final int CROP_PICTURE_REQUEST = 0x3;


    private static final String TEMP_FILE_NAME = "temp_icon2.jpg";
    /**
     * Save the path of photo cropping is completed
     */
    private Uri icon_path;
    private Uri camera_path;


    //选择头像
    private void showImagePopwindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_image, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);

        Button btnCamera = (Button) contentView.findViewById(R.id.btn_camera_pop_camera);
        Button btnAlbum = (Button) contentView.findViewById(R.id.btn_camera_pop_album);
        Button btnCancel = (Button) contentView.findViewById(R.id.btn_camera_pop_cancel);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_camera_pop_camera:
                        //检查权限(6.0以上做权限判断)
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                                requestPermissions(PERMISSIONS, 1000);
                            } else {
                                openCamera();
                            }
                        } else {
                            openCamera();
                        }
                        break;
                    case R.id.btn_camera_pop_album:
                        //检查权限(6.0以上做权限判断)
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                                requestPermissions(new String[]{PERMISSIONS[1]}, 1100);
                            } else {
                                selectFromAlbum();
                            }
                        } else {
                            selectFromAlbum();
                        }
                        break;
                    case R.id.btn_camera_pop_cancel:

                        break;
                }
                popWindow.dismiss();
            }
        };
        btnCamera.setOnClickListener(listener);
        btnAlbum.setOnClickListener(listener);
        btnCancel.setOnClickListener(listener);

        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void selectFromAlbum() {
        dir = getExternalFilesDir("user_icon");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            icon_path = FileProvider.getUriForFile(PartnerApplicationActivity.this,
                    getPackageName() + ".fileprovider", new File(dir, TEMP_FILE_NAME));
            camera_path = FileProvider.getUriForFile(PartnerApplicationActivity.this,
                    getPackageName() + ".fileprovider", new File(dir, "camera_pic2.jpg"));
        } else {
            icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));
            camera_path = Uri.fromFile(new File(dir, "camera_pic2.jpg"));
        }
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        Intent intentFromGallery = new Intent();
//        intentFromGallery.setType("image/*");
//        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, CODE_GALLERY_REQUEST);


    }

    //打开系统相机
    private File dir;

    private void openCamera() {
        dir = getExternalFilesDir("user_icon");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            icon_path = FileProvider.getUriForFile(getApplicationContext(),
                    getPackageName() + ".fileprovider", new File(dir, TEMP_FILE_NAME));
            camera_path = FileProvider.getUriForFile(getApplicationContext(),
                    getPackageName() + ".fileprovider", new File(dir, "camera_pic2.jpg"));
        } else {
            icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));
            camera_path = Uri.fromFile(new File(dir, "camera_pic2.jpg"));
        }
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, camera_path);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intentFromCapture.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case CODE_GALLERY_REQUEST:
           /*     if ("fan".equals(type)) {
                    cropImage(data.getData(), 68, 75, 750, 750, CROP_PICTURE_REQUEST);
                } else {
                    cropImage(data.getData(), 68, 75, 750, 750, CROP_PICTURE_REQUEST);
                }*/
                if ("fan".equals(type)) {
                    cropImage(data.getData(), 0, 0, 999, 999, CROP_PICTURE_REQUEST);
                } else {
                    cropImage(data.getData(), 0, 0, 999, 999, CROP_PICTURE_REQUEST);
                }
                break;
            case CODE_CAMERA_REQUEST:
                if ("fan".equals(type)) {
                    cropImage(camera_path, 0, 0, 999, 999, CROP_PICTURE_REQUEST);
                } else {
                    cropImage(camera_path, 0, 0, 999, 999, CROP_PICTURE_REQUEST);
                }
            case CROP_PICTURE_REQUEST:
                bitmap = decodeUriAsBitmap(icon_path);
                Imagefile = BitmapUtils.saveBitmapFile(bitmap, "camera");
                mPicModel.getData(Imagefile, type, this);
                bitmap = null;
                break;
        }
    }
    /**
     * According to the incoming a length-width ratio began to cut out pictures
     *
     * @param uri Image source
     */
    private void cropImage(Uri uri, int aspectX, int aspectY, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // Set the cutting
        intent.putExtra("crop", "true");
        // aspectX , aspectY :In proportion to the width of high
        if (android.os.Build.MODEL.contains("HUAWEI")) {//华为特殊处理 不然会显示圆
            intent.putExtra("aspectX", 1600);
            intent.putExtra("aspectY", 1000);
        } else {
        /*    intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);*/
            intent.putExtra("aspectX", aspectX);
            intent.putExtra("aspectY", aspectY);
        }


        // outputX , outputY : High cutting image width
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale",true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, icon_path);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            addurlPram(this, intent, camera_path, icon_path);
        }
        startActivityForResult(intent, requestCode);
    }

    private void addurlPram(Activity activity, Intent intent, Uri... uris) {
        List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            for (Uri uri : uris) {
                activity.grantUriPermission(packageName, uri,
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
        }
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 1000:
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                    TemplatePopupwindowUtils.showPermissionsPopupWindow(PartnerApplicationActivity.this, "当前功能缺失必要权限", "请手动开启");
                } else {
                    openCamera();
                }
                break;
            case 1100:
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS[1])) {
                    TemplatePopupwindowUtils.showPermissionsPopupWindow(PartnerApplicationActivity.this, "当前功能缺失必要权限", "请手动开启");
                } else {
                    selectFromAlbum();
                }
                break;
        }
    }
    //上传图片成功
    @Override
    public void inputSuccess(Object object, String type) {
        JSONObject jsonObject = (JSONObject) object;
       // ToastUtils.makeToastShort(jsonObject.optString("msg"));

        if ("zheng".equals(type)) {
            zhengURL = jsonObject.optString("res");
            if (ASUtils.isCanUse(zhengURL)) {
                Picasso.with(this).load(zhengURL).into(mIvZheng);
            } else {
                mIvZheng.setImageBitmap(bitmap); // 将裁剪后的照片显示出来
            }
        } else if ("fan".equals(type)) {
            fanURL = jsonObject.optString("res");
            if (ASUtils.isCanUse(fanURL)) {
                Picasso.with(this).load(fanURL).into(mIvFan);
            } else {
                mIvFan.setImageBitmap(bitmap); // 将裁剪后的照片显示出来
            }
        }
        ToastUtils.makeToastShort("图片上传成功");
    }

    @Override
    public void inputError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    //申请合伙人成功
    @Override
    public void applyForPartnerSucess(Object object) {
     //   Log.e("applyForPartner:", "申请合伙人成功");
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

        //  ToastUtils.makeToastShort("申请成功");
      /*  //获取申请合伙人数据
        mModel.getPartnerApplicationData(this);*/
        if ("1".equals(mIspay)) {
            Intent intent = new Intent(this, AuditStateActivity.class);
            startActivity(intent);
        } else {
            startActivity(new Intent(this, PartnerCheckstandActivity.class));
        }

    }

    //申请合伙人失败
    @Override
    public void applyForPartnerError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }


    // 获取合伙人信息成功

    @Override
    public void getPartnerApplicationSucess(Object object) {
        Log.e("getPartnerSucess:", "获取合伙人信息成功");
        mPartnerApplicationBean = (PartnerApplicationBean) object;
        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        editor.putString("username", mPartnerApplicationBean.getUsername());
        editor.putString("mobile", mPartnerApplicationBean.getMobile());
        editor.putString("address", mPartnerApplicationBean.getAddress());
        editor.putString("userid", mPartnerApplicationBean.getUserid());
        editor.putString("imguserida", mPartnerApplicationBean.getImguserida());
        editor.putString("imguseridb", mPartnerApplicationBean.getImguseridb());
        editor.putString("citys", mTvAddress.getText().toString().trim());
        mDenyReason = mPartnerApplicationBean.getDenyReason();
        editor.putString("denyReason", mDenyReason);
        editor.apply();
        //   showViews();
        showView();

    }

    //获取合伙人信息失败
    @Override
    public void getPartnerApplicationError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
         ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
    //修改城市合伙人信息
    @Override
    public void changePartnerApplicationSucess(Object object) {
        Log.e("changePartner:", "修改城市合伙人信息成功");
    //    ToastUtils.makeToastShort("提交成功");
        //   mModel.getPartnerApplicationData(this);
        if ("1".equals(mIspay)) {
            Intent intent = new Intent(this, AuditStateActivity.class);
            startActivity(intent);
        } else {
            startActivity(new Intent(this, PartnerCheckstandActivity.class));
        }
    }
    @Override
    public void changePartnerApplicationError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
           ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    @Override
    public void beCityPartnersSuccess(Object object) {
        Log.e("beCityPartners:", "获取信息成功");
        mPartnersData = (BeCityPartnersData) object;
        ShowViews();

    }

    private void ShowViews() {
        Check = mPartnersData.getCheck();
        Ispay = mPartnersData.getIspay();

    }

    @Override
    public void beCityPartnersError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void getAddress(Object object) {
        address = (Address) object;
        pid.clear();
        for (Address.DataBean dataBean : address.getData()) {
            pid.add(dataBean.getText());
        }

    }
}
